package com.netty.client.handler;

import com.netty.entity.Message;
import com.netty.entity.Person;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TestClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try{
            ByteBuf readBuffer=(ByteBuf)msg;
            byte[] tempDatas=new byte[readBuffer.readableBytes()];
            readBuffer.readBytes(tempDatas);
            System.out.println("from server:"+new String(tempDatas,"UTF-8"));
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String line=br.readLine();
            if("person".equals(line)){
                Person person = new Person();
                person.setAge(11);
                person.setName("许荣北");
                ctx.channel().writeAndFlush(person);
                //ctx.writeAndFlush(person);
            }else if("message".equals(line)) {
                Message message = new Message();
                message.setTitle("read");
                message.setContent("来消息了，你好");
                ctx.channel().writeAndFlush(message);
                //ctx.writeAndFlush(message);
            }else {
                ctx.channel().writeAndFlush(Unpooled.copiedBuffer(line.getBytes("UTF-8")));
                //ctx.writeAndFlush(Unpooled.copiedBuffer(line.getBytes("UTF-8")));
            }

        }
        finally{
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("client exceptionCanght method run...");
        ctx.close();
    }
}
